package com.jee.ssm.modules.dict.app;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.jee.ssm.common.socket.guideScreen.SocketHandle;
import com.jee.ssm.common.socket.guideScreen.SocketServer;
import com.jee.ssm.common.utils.HttpUtils;
import com.jee.ssm.common.utils.ImageWordUtils;
import com.jee.ssm.common.utils.UUIDFactory;
import com.jee.ssm.common.utils.hik8200.artemis.sdk.config.ArtemisConfig;
import com.jee.ssm.common.utils.hik8200.common.constant.VideoConstant;
import com.jee.ssm.common.utils.hik8200.common.exception.VideoRuntimeException;
import com.jee.ssm.common.utils.hik8200.common.webapi.WebApiResponse;
import com.jee.ssm.common.utils.mq.jms.SimpleTestMain;
import com.jee.ssm.model.ccb.PayReceive;
import com.jee.ssm.model.ccb.QueryReceive;
import com.jee.ssm.model.hik8200.bo.AgreementBo;
import com.jee.ssm.model.hik8200.dto.AgreementDto;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.modules.dict.services.DictService;
import com.jee.ssm.modules.hikBill.services.HikBillService;

import COM.CCB.EnDecryptAlgorithm.MCipherEncryptor;

/**
* 数据字典管理 客户端 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/app/dict")
public class AppDictController {
	
	private Logger logger = Logger.getLogger(AppDictController.class);
	
	@RequestMapping(value = "/mergeTwoPhoto", method = RequestMethod.GET)
	@ResponseBody
	public Tip mergeTwoPhoto(HttpServletRequest request) {
		String url = "/images/card/";
        String path = request.getServletContext().getRealPath(url);
        String name = "new.jpg";
		String[] files = new String[2];
		files[0] = request.getServletContext().getRealPath("/images/card/1.jpg");
		files[1] = request.getServletContext().getRealPath("/images/card/1.jpg");
        File[] src = new File[2];
        BufferedImage[] images = new BufferedImage[2];
        int[][] ImageArrays = new int[2][];
        for (int i = 0; i < 2; i++) {
            try {
                src[i] = new File(files[i]);
                images[i] = ImageIO.read(src[i]);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            int width = images[i].getWidth();
            int height = images[i].getHeight();
            ImageArrays[i] = new int[width * height];
            ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);
        }
        int newHeight = 0;
        int newWidth = 0;
        for (int i = 0; i < images.length; i++) {
            // 横向
            newHeight = newHeight > images[i].getHeight() ? newHeight : images[i].getHeight();
            newWidth += images[i].getWidth();
        }

        // 生成新图片
        try {
            BufferedImage ImageNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
//            int height_i = 0;
            int width_i = 0;
            for (int i = 0; i < images.length; i++) {
                ImageNew.setRGB(width_i, 0, images[i].getWidth(), newHeight, ImageArrays[i], 0, images[i].getWidth());
                width_i += images[i].getWidth();
            }
            
            //输出想要的图片
            ImageIO.write(ImageNew, "jpg", new File(path, name));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new Tip(path + name);
	}
	
	 public static void saveToFile(String destUrl, String path) {
		 FileOutputStream fos = null;
		 BufferedInputStream bis = null;
		 HttpURLConnection httpUrl = null;
		 URL url = null;
		 int BUFFER_SIZE = 1024;
		 byte[] buf = new byte[BUFFER_SIZE];
		 int size = 0;
		 try {
			 url = new URL(destUrl);
			 httpUrl = (HttpURLConnection) url.openConnection();
			 httpUrl.connect();
			 bis = new BufferedInputStream(httpUrl.getInputStream());
			 fos = new FileOutputStream(path);
			 while ((size = bis.read(buf)) != -1) {
				 fos.write(buf, 0, size);
			 }
			 fos.flush();
		 } catch (IOException e) {
			 e.printStackTrace();
		 } catch (ClassCastException e) {
			 e.printStackTrace();
		 } finally {
			 try {
				 fos.close();
				 bis.close();
				 httpUrl.disconnect();
			 } catch (IOException e) {
				 e.printStackTrace();
			 } catch (NullPointerException e) {
				 e.printStackTrace();
			 }
		 }
	 }
	 
	 public static void saveFile(String myurl, String path) {
		 //输入一个图片网址，将其获取到桌面
		 //1.处理网址URL
		 //2.通过网址打开网络链接
		 //3.判断网络响应
		 //4.读取图片文件流
		 //5.创建图片存储文件路径，将文件流写进新创建的文件
		 HttpURLConnection connection=null;
		 URL url = null;
		 try {
			 url = new URL(myurl);
			 connection = (HttpURLConnection)url.openConnection();
			 int code = connection.getResponseCode();
			 if(code == 200) {  //响应成功
				 BufferedImage image = ImageIO.read(connection.getInputStream()); //读取图片文件流
				 ImageIO.write(image, "png", new File(path));  //将图片写进创建的路径
			 }
		 } catch (MalformedURLException e) {
			 e.printStackTrace();
		 } catch (IOException e) {
			 e.printStackTrace();
		 }
	 }
	 
	 public static void main(String[] args) throws Exception {
//		 saveToFile("http://jiaotong.baidu.com/guidingscreen/screen/image?id=1596", "C:\\Users\\Administrator\\Pictures\\Camera Roll\\f.jpg");
//		 createImage("剩余30车位", new Font("宋体", Font.BOLD, 30), new File("C:\\Users\\Administrator\\Pictures\\Camera Roll\\a.png"), 100, 200);

	 }
	 
	 @RequestMapping(value = "/getData", method = RequestMethod.GET)
	 public String getData(Model model, HttpServletRequest request, String number, String word) throws FileNotFoundException, IOException {
		 long s = System.currentTimeMillis();
		 String url = "/images/card/" + s + "/";
		 String path = request.getServletContext().getRealPath(url);
		 String fileName = number + ".jpg";
		 File file = new File(path);
		 if(!file.exists() && !file.isDirectory()) {
			 file.mkdirs();
		 }
		 saveToFile("http://jiaotong.baidu.com/guidingscreen/screen/image?id=" + number, path + fileName);
		 File f = new File(path + fileName);
		 BufferedImage img =ImageIO.read(new FileInputStream(f));
		 int width = img.getWidth();
		 int height1 = img.getHeight();
		 BufferedImage wordImg = ImageWordUtils.getPictureByWord(word, width);
		 int height2 = wordImg.getHeight();
		 
		 BufferedImage tag = new BufferedImage(width, height1 + height2, BufferedImage.TYPE_INT_RGB);
		 
		 Graphics g = tag.createGraphics();
		 g.drawImage(img, 0, 0, width, height1, null);
		 g.drawImage(wordImg, 0, height1, width , height2, null);
		 
		 String result = path + number + "_word.jpg";
		 ImageIO.write(tag, "JPEG", new File(result));
		 model.addAttribute("tip", new Tip(url + number + "_word.jpg"));
		 return "manager/img";
	 }
	 
	 // 根据str,font的样式以及输出文件目录
	 public static void createImage(String str, Font font, File outFile, Integer width, Integer height) throws Exception {
		 // 创建图片
		 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		 Graphics g = image.getGraphics();
		 g.setClip(0, 0, width, height);
		 g.setColor(Color.black);
		 g.fillRect(0, 0, width, height);// 先用黑色填充整张图片,也就是背景
		 g.setColor(Color.red);// 在换成黑色
		 g.setFont(font);// 设置画笔字体
		 //用于获得垂直居中y
		 Rectangle clip = g.getClipBounds();
		 FontMetrics fm = g.getFontMetrics(font);
		 int ascent = fm.getAscent();
		 int descent = fm.getDescent();
		 int y = (clip.height - (ascent + descent)) / 2 + ascent;
		 for (int i = 0; i < 6; i++) {// 256 340 0 680
			 g.drawString(str, i * 680, y);// 画出字符串
		 }
		 g.dispose();
		 ImageIO.write(image, "png", outFile);// 输出png图片
	 }
	 
	 @RequestMapping(value = "/getAgreement", method = RequestMethod.GET)
	 @ResponseBody
	 public WebApiResponse<AgreementDto> getAgreement() {
		 
		 try {
			 String url = "60.208.57.118:9999";
	         String[] arr = url.split(":");
	         String appKey = "26208115";
	         String appSceret = "Q9GM11oUW74AkOcc0Gq9";
	         String schema = "https";
	         String videoClietSchema = "https";
	         
	         ArtemisConfig a = new ArtemisConfig(url, appKey, appSceret);

	         AgreementBo agreementBo = dictService.getSecurityAgreement(a, schema);

	         String time = agreementBo.getTime();
	         String timeSecret = agreementBo.getTimeSecret();
	         String appSecretSecurity = agreementBo.getAppSecret();
			
	         String ip = arr[0];
	         String port = null;

	         if (arr.length == 1) {
	        	 if (schema.equals("https")) {
	        		 port = "443";
	        	 } else {
	        		 port = "80";
	        	 }
	         } else {
	        	 port = arr[1];
	         }
	         return new WebApiResponse<AgreementDto>(VideoConstant.HttpStatusDict.SUCCESS_CODE,
	        		 VideoConstant.HttpMsgDict.SUCCESS_MSG, new AgreementDto(ip, port, appKey,appSecretSecurity, time, timeSecret, videoClietSchema));
		 } catch (VideoRuntimeException e) {
			 logger.info("Get agreement"+ VideoConstant.LogConstant.HANDLE_FAILED);
		 }
		 return new WebApiResponse<AgreementDto>(VideoConstant.HttpStatusDict.ERROR_CODE, VideoConstant.HttpMsgDict.ERROR_MSG, null);
	 }
	 
	 @RequestMapping(value = "/monitor", method = RequestMethod.GET)
	 public String monitor(Model model, String number) {
		 model.addAttribute("monitor", getAgreement());
		 model.addAttribute("number", number);
		 return "manager/present/video";
	 }
	 
	 @RequestMapping(value = "/getImage", method = RequestMethod.GET)
	 public String getImage(Model model, HttpServletRequest request, String name, String number, String word) throws FileNotFoundException, IOException {
		 long s = System.currentTimeMillis();
		 String url = "/images/card/" + s + "/";
		 String path = request.getServletContext().getRealPath(url);
		 String fileName = number + ".jpg";
		 File file = new File(path);
		 if(!file.exists() && !file.isDirectory()) {
			 file.mkdirs();
		 }
		 saveToFile("http://jiaotong.baidu.com/guidingscreen/screen/image?id=" + number, path + fileName);
		 File f = new File(path + fileName);
		 BufferedImage img =ImageIO.read(new FileInputStream(f));
		 int width = img.getWidth();
		 int height1 = img.getHeight();
		 
		 String[] words = word.split(";");
		 
		 if(words.length == 2) {
			 BufferedImage wordImg1 = ImageWordUtils.getPictureByWord(words[0], width);
			 BufferedImage wordImg2 = ImageWordUtils.getPictureByWord(words[1], width);
			 int height2 = wordImg1.getHeight();
			 int height3 = wordImg2.getHeight();
			 
			 BufferedImage tag = new BufferedImage(width, height1 + height2 + height3, BufferedImage.TYPE_INT_RGB);
			 
			 Graphics g = tag.createGraphics();
			 g.drawImage(wordImg1, 0, 0, width, height2, null);
			 g.drawImage(img, 0, height2, width, height1, null);
			 g.drawImage(wordImg2, 0, height1 + height2, width , height3, null);
			 
			 String result = path + name + "_" + number + "_word.jpg";
			 ImageIO.write(tag, "JPEG", new File(result));
			 model.addAttribute("tip", new Tip(url + name + "_" + number + "_word.jpg"));
		 } else {
			 model.addAttribute("tip", new Tip(1, "注意分号个数"));
		 }

		 return "manager/img";
	 }
	 
	 @RequestMapping(value = "/openOrClose", method = RequestMethod.GET)
	 @ResponseBody
	 public Tip openOrClose(Integer flag) {
		 Tip tip = new Tip("发送成功");
		 SocketHandle s = SocketServer.socketMap.get("Pluto2012");
		 if(s != null) {
			 s.openOrClose(flag);
		 } else {
			 tip = new Tip(1, "设备不在线");
		 }
		 return tip;
	 }
	 
	 @RequestMapping(value = "/cleanAll", method = RequestMethod.GET)
	 @ResponseBody
	 public Tip cleanAll() {
		 Tip tip = new Tip("发送成功");
		 SocketHandle s = SocketServer.socketMap.get("Pluto2012");
		 if(s != null) {
			 s.cleanAll();
		 } else {
			 tip = new Tip(1, "设备不在线");
		 }
		 return tip;
	 }
	 
	 @RequestMapping(value = "/sendFile", method = RequestMethod.GET)
	 @ResponseBody
	 public Tip sendFile(String name) {
		 Tip tip = new Tip("发送成功");
		 SocketHandle s = SocketServer.socketMap.get("Pluto2012");
		 if(s != null) {
			 try {
				 List<Byte> list = getFileInfo("C:\\Users\\ASUS\\Desktop\\诱导屏\\" + name + ".jpg");
				 s.sendFileName(list.size() - 1, name + ".jpg");
				 s.sendFile(list);
				 
			} catch (IOException e) {
				e.printStackTrace();
			}
			 
		 } else {
			 tip = new Tip(1, "设备不在线");
		 }
		 return tip;
	 }
	 
	 @RequestMapping(value = "/sendPlay", method = RequestMethod.GET)
	 @ResponseBody
	 public Tip sendPlay(Integer n) {
		 Tip tip = new Tip("发送成功");
		 SocketHandle s = SocketServer.socketMap.get("Pluto2012");
		 if(s != null) {
			 try {
				 List<Byte> playlist = getFileInfo("C:\\Users\\ASUS\\Desktop\\诱导屏\\play00" + n + ".lst");
				 s.sendFileName(playlist.size() + 1, "play00" + n + ".lst");
				 s.sendFile(playlist);
			} catch (IOException e) {
				e.printStackTrace();
			}
			 
		 } else {
			 tip = new Tip(1, "设备不在线");
		 }
		 return tip;
	 }
	 
	 @RequestMapping(value = "/play", method = RequestMethod.GET)
	 @ResponseBody
	 public Tip play(Integer n) {
		 Tip tip = new Tip("发送成功");
		 SocketHandle s = SocketServer.socketMap.get("Pluto2012");
		 if(s != null) {
			 s.play(n);
		 } else {
			 tip = new Tip(1, "设备不在线");
		 }
		 return tip;
	 }
	 
	 @RequestMapping(value = "/send", method = RequestMethod.GET)
	 @ResponseBody
	 public Tip send(Integer n, String name) {
		 Tip tip = new Tip("发送成功");
		 SocketHandle s = SocketServer.socketMap.get("Pluto2012");
		 if(s != null) {
			 s.cleanAll();
			 try {
				 List<Byte> playlist = getFileInfo("C:\\Users\\ASUS\\Desktop\\诱导屏\\play00" + n + ".lst");
				 s.sendFileName(playlist.size() + 1, "play00" + n + ".lst");
				 s.sendFile(playlist);
				 
				 List<Byte> list = getFileInfo("C:\\Users\\ASUS\\Desktop\\诱导屏\\" + name + ".jpg");
				 s.sendFileName(list.size() - 1, name + ".jpg");
				 s.sendFile(list);
				 
			} catch (IOException e) {
				e.printStackTrace();
			}
			 s.play(n);
		 } else {
			 tip = new Tip(1, "设备不在线");
		 }
		 return tip;
	 }

	 public List<Byte> getFileInfo(String url) throws IOException {
		 
		 List<Byte> bytes = new ArrayList<>();
		 byte[] f = InputStream2ByteArray(url);
		 for(byte y : f) {
			 if(y == 170 || y == -86) {
				 bytes.add((byte)0xEE);
				 bytes.add((byte)0x0A);
			 } else if(y == 204 || y == -52) {
				 bytes.add((byte)0xEE);
				 bytes.add((byte)0x0C);
			 } else if(y == 238 || y == -18) {
				 bytes.add((byte)0xEE);
				 bytes.add((byte)0x0E);
			 } else {
				 bytes.add(y);
			 }
		 }
		 return bytes;
	}
	 
	private byte[] InputStream2ByteArray(String filePath) throws IOException {
		InputStream in = new FileInputStream(filePath);
		byte[] data = toByteArray(in);
		in.close();
		return data;
	}
		 
	private byte[] toByteArray(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}
	
	@RequestMapping(value = "/jms", method = RequestMethod.GET)
	@ResponseBody
	public Tip jms() {
		Tip tip = new Tip();
		try {
			SimpleTestMain.jsm();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tip = new Tip(1, "异常了");
			
		}
		return tip;
	}
	
	@RequestMapping(value = "/checkStatus", method = RequestMethod.GET)
	@ResponseBody
	public Tip checkStatus() {
		Tip tip = new Tip();
		String url = "https://ibsbjstar.ccb.com.cn/CCBIS/B2CMainPlat_00_ENPAY";
		
		String MERCHANTID = "105910200793152";
		
		String POSID = "021875917";
		
		String BRANCHID = "130000000";
		
		String AUTHNO = "冀C2W135";
		
		String strSrcParas = "MERFLAG=1&MERCHANTID=" + MERCHANTID + "&POSID=" + POSID + "&BRANCHID=" + BRANCHID + "&AUTHNO=" + AUTHNO + "&TXCODE=WGZF01";
		
		logger.info(strSrcParas);
		
		String strKey = "d5475cd40d0e98cddaa3dcf9020111";
		
		MCipherEncryptor ccbEncryptor = new MCipherEncryptor(strKey);

		try {
			String ccbParam = ccbEncryptor.doEncrypt(strSrcParas);
			
			logger.info(ccbParam);
			
			NameValuePair[] data = {
					new NameValuePair("MERFLAG", "1"),
					new NameValuePair("MERCHANTID", MERCHANTID),
					new NameValuePair("POSID", POSID),
					new NameValuePair("BRANCHID", BRANCHID),
					new NameValuePair("AUTHNO", AUTHNO),
					new NameValuePair("TXCODE", "WGZF01"),
					new NameValuePair("ccbParam", ccbParam)
			};
			
			String result = HttpUtils.doPost(url, data);
			QueryReceive qr = JSONObject.parseObject(result, QueryReceive.class);
			if("1".equals(qr.getAUTHSTATUS())) {
				//查询结果1为已绑定信用卡，这里处理结果
			}
			tip.setData(qr);
		} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | ShortBufferException
				| IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
				| InvalidAlgorithmParameterException | UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tip = new Tip(1, "加密失败");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tip = new Tip(1, "请求异常");
		}
		
		return tip;
	}
	
	@RequestMapping(value = "/payByCCB", method = RequestMethod.GET)
	@ResponseBody
	public Tip payByCCB(String AMOUNT) {
		Tip tip = new Tip();
		String url = "https://ibsbjstar.ccb.com.cn/CCBIS/B2CMainPlat_00_ENPAY";
		
		String MERCHANTID = "105910200793152";
		
		String POSID = "021875917";
		
		String BRANCHID = "130000000";
		
		String ORDERID = UUIDFactory.get32Id().substring(0, 30);
		
		String AUTHNO = "冀CGB112";
		
		String strSrcParas = "MERFLAG=1&MERCHANTID=" + MERCHANTID + "&POSID=" + POSID + "&BRANCHID=" + BRANCHID + "&ORDERID=" + ORDERID +"&AUTHNO=" + AUTHNO + "&AMOUNT=" + AMOUNT + "&TXCODE=WGZF00";
		
		String strKey = "d5475cd40d0e98cddaa3dcf9020111";
		
		MCipherEncryptor ccbEncryptor = new MCipherEncryptor(strKey);

		try {
			String ccbParam = ccbEncryptor.doEncrypt(strSrcParas);
			
			NameValuePair[] data = {
					new NameValuePair("MERFLAG", "1"),
					new NameValuePair("MERCHANTID", MERCHANTID),
					new NameValuePair("POSID", POSID),
					new NameValuePair("BRANCHID", BRANCHID),
					new NameValuePair("ORDERID", ORDERID),
					new NameValuePair("AUTHNO", AUTHNO),
					new NameValuePair("AMOUNT", AMOUNT),
					new NameValuePair("TXCODE", "WGZF00"),
					new NameValuePair("ccbParam", ccbParam)
			};
			String result = HttpUtils.doPost(url, data);
			PayReceive pr = JSONObject.parseObject(result, PayReceive.class);
			if("Y".equals(pr.getRESULT())) {
				// TODO 返回扣费成功，这里处理结果
			}
			tip.setData(pr);
		} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | ShortBufferException
				| IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
				| InvalidAlgorithmParameterException | UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tip = new Tip(1, "加密失败");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tip = new Tip(1, "请求异常");
		}
		
		return tip;
	}
	
    //---------------------------- property -------------------------------

    @Resource
    private DictService dictService;
    
    @Resource
    private HikBillService hikBillService;

}
